package com.hxexp.weixin.mvc.userinfo.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.cache.TokenCacheManager;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.constant.Errcode;
import com.hxexp.weixin.constant.Gender;
import com.hxexp.weixin.constant.IdentificationType;
import com.hxexp.weixin.constant.PassengerType;
import com.hxexp.weixin.constant.StringConstant;
import com.hxexp.weixin.hpe.api.login.model.LoginResultBean;
import com.hxexp.weixin.hpe.api.userupdate.model.UserUpdateParamBean;
import com.hxexp.weixin.hpe.api.userupdate.model.UserUpdateResultBean;
import com.hxexp.weixin.mvc.userinfo.model.UserInfoFormBean;
import com.hxexp.weixin.mvc.userinfo.service.UserInfoService;

import net.sf.cglib.beans.BeanCopier;

/**
 * 用户信息控制器
 *
 * @author li.jiang
 *
 */
@Controller
@RequestMapping(value = "/userinfo")
public final class UserInfoController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private TokenCacheManager tokenCacheManager;
    private final BeanCopier beanCopier = BeanCopier.create(UserInfoFormBean.class, UserUpdateParamBean.class, false);
    private final BeanCopier beanCopier2 = BeanCopier.create(UserInfoFormBean.class, LoginResultBean.class, false);
    /**
     * 设置页面需要的常量
     *
     * @return
     */
    @ModelAttribute("constant")
    public Map<String, String> setConstant() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("idcard", IdentificationType.IDCARD);// 身份证
        map.put("officercard", IdentificationType.OFFICERCARD); // 军官证
        map.put("errcode_success", String.valueOf(Errcode.SUCCESS));

        return map;
    }

    /**
     * 编辑用户信息页面
     *
     * @param token
     *            登录用户令牌
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit")
    public String editUserInfo(@CookieValue(value = CookieName.TOKEN, defaultValue = StringConstant.BLANK) String token, String mobile, Model model) {
        // 从缓存中获取登陆用户信息
        LoginResultBean loginResultBean = tokenCacheManager.getUserFromCache(token);
        loginResultBean.setMobile(mobile);
        model.addAttribute("loginResult", loginResultBean);
        model.addAttribute("genderMap", Gender.CODE_NAME_MAP);
        model.addAttribute("identificationMap", IdentificationType.CODE_NAME_MAP);
        model.addAttribute("passengerMap", PassengerType.CODE_NAME_MAP);
        model.addAttribute("token", token);

        return "userinfo_update";
    }

    /**
     * 更新用户信息
     *
     * @param userUpdateParam
     *            用户信息更新参数
     * @return 更新结果
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public UserUpdateResultBean updateUserInfo(UserInfoFormBean userInfoFormBean) {
        UserUpdateParamBean userUpdateParam = new UserUpdateParamBean();
        UserUpdateResultBean userUpdateResult = new UserUpdateResultBean();

        beanCopier.copy(userInfoFormBean, userUpdateParam, null);
        try {
            userUpdateResult = userInfoService.updateUserInfo(userUpdateParam);
            // 更新用户成功后，将登录用户信息更新到缓存
            if (userUpdateResult.getErrcode() == Errcode.SUCCESS) {
                LoginResultBean loginResultBean = new LoginResultBean();
                beanCopier2.copy(userInfoFormBean, loginResultBean, null);
                tokenCacheManager.saveUserToCache(userInfoFormBean.getToken(), loginResultBean);
            }
        } catch (ServiceException e) {
            LOGGER.error("更新用户信息发生异常", e);
            userUpdateResult.setErrcode(Errcode.FAIL);
            userUpdateResult.setErrmsg("服务器内部异常，更新用户信息失败");
        }

        return userUpdateResult;
    }

}
